package com.fingard.avatar.website.exception;

import cn.hutool.core.util.StrUtil;
import com.fingard.avatar.website.model.bean.ResultContext;
import com.fingard.avatar.website.model.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 徐一涛
 * @date 2022/4/26
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public ResultContext<Void> handleBizException(BizException e) {
        return ResultContext.fail(ResultCode.BUSINESS_ERROR, e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultContext<Void> handleException(MethodArgumentNotValidException e) {
        StringBuffer sb = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(
                error -> {
                    String fieldName = ((FieldError) error).getField();
                    String errorMessage = error.getDefaultMessage();
                    if(sb.length() != 0) {
                        sb.append(StrUtil.LF);
                    }
                    sb.append(StrUtil.BRACKET_START).append(fieldName).append(StrUtil.BRACKET_END).append(StrUtil.C_COLON).
                            append(errorMessage);
                }
        );
        return ResultContext.fail(ResultCode.PARAMS_ERROR, sb.toString());
    }

    @ExceptionHandler(BindException.class)
    public ResultContext<Void> handleBindException(BindException e) {
        StringBuffer sb = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(
                error -> {
                    String fieldName = ((FieldError) error).getField();
                    String errorMessage = error.getDefaultMessage();
                    if(sb.length() != 0) {
                        sb.append(StrUtil.LF);
                    }
                    sb.append(StrUtil.BRACKET_START).append(fieldName).append(StrUtil.BRACKET_END).append(StrUtil.C_COLON).
                            append(errorMessage);
                }
        );
        return ResultContext.fail(ResultCode.PARAMS_ERROR, sb.toString());
    }

    @ExceptionHandler(Exception.class)
    public ResultContext<Void> handleException(Exception e) {
        return ResultContext.fail(ResultCode.SYSTEM_EXCEPTION, e.getMessage());
    }
}
